<?php

namespace App\Admin\Http\Controllers\Business;


use App\Admin\Eloquent\OrganizationalUser;
use App\Admin\Eloquent\User;
use App\Eloquent\User as SuperUser;
use App\Admin\Eloquent\UserInfo;
use App\Eloquent\UserInfo as SuperUserInfo;
use App\Admin\Http\Controllers\Controller;
use App\Admin\Http\Requests\OrganizationalUserRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mockery\CountValidator\Exception;
use AuditMemberInfos;
use App\Http\Controllers\Utils\UtilsController;
use App\Admin\Eloquent\Code;
use Log;
use CreateActivateMember;
use Flash;
use QueryBalance;
use SetPayPassword;

class OrganizationalManagerController extends Controller
{
  /**
   * 访问级别
   *  
   *  0 管理员
   *  1 销售总监
   *  2 团队经理
   *  3 瑞信营销,做特殊处理
   */
  protected $access_level;

  protected $RXYX_CODE = '9DS12W';  //瑞信营销 机构code

  /**
   * 访问的前台用户(如果存在)
   * @var [type]
   */
  protected $frontUser;

  /**
   * 查询的机构
   */
  protected $org_code;

  /**
   * 查询的部门
   */
  protected $dept_code;

  /**
   * 后台用户
   */
  protected $user;

  /**
   * 初始化
   * 
   * @return [type] [description]
   */
  public function __init(){
    $this->accessInfo();

    //共享变量到视图
    view()->share('admin_user',$this->user);
    view()->share('rxyx_code',$this->RXYX_CODE);
  }

  /**
   * 获取访问信息
   * 
   * @return [type] [description]
   */
  protected function accessInfo(){
    $user = $this->currentUser();

    $this->user = $user;
    //拆分用户名,获取用户前台用户
    $name = substr($user->username, 0, 4);

    if($name == 'bbl_'){
      $name = substr($user->username, 4);
      //查找前台用户
      if($frontUser = SuperUser::toUser($name)){
        $this->frontUser = $frontUser;
        $this->org_code = $frontUser->userInfo->org_code;
        $this->dept_code = $frontUser->userInfo->dept_code;
        //判断用户角色
      }
    }

    //判断用户的角色
    if($user->hasRole('CSO')){
      $this->access_level = 1;
    }else if($user->hasRole('Team_manager')){
      $this->access_level = 2;
    }
    else if($user->hasRole('RXYX'))
    {
      $this->access_level = 3;
    }
    else
    {
      $this->access_level = 0;
    }
  }
	/**
	 * 根据对应的访问权限处理
	 * 
	 * @param  array  $queryArgs [description]
	 * @return [type]            [description]
	 */
	protected function queryRestriction(array $queryArgs){

		if(!empty($this->org_code) && ($this->access_level == 1 or $this->access_level == 2))
			$queryArgs['org_code'] = $this->org_code;

		if(!empty($this->dept_code) && $this->access_level == 2)
			$queryArgs['dept_code'] = $this->dept_code;

        if(empty($queryArgs['cl_time']))
            $queryArgs['cl_time'] = date('Y-m-d H:i:s');

        if(empty($queryArgs['start_time']))
            $queryArgs['start_time'] = date('Y-m-d ').'00:00:00';

        if(empty($queryArgs['end_time']))
            $queryArgs['end_time'] = date('Y-m-d ').'23:59:59';

		return $queryArgs;
	}

	/**
	 * 统计机构存量,总人数，
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
    public function orgList(Request $request, String $download = "")
    {
        $query = $this->queryRestriction($request->only('org_name', 'org_code', 'start_time', 'end_time'));

        $sql = "SELECT a.org_code,
        count(distinct(jjrb.user_id)) AS broker_count,
        count(distinct(jjrb_two.user_id)) AS broker_two_count,
       count(a.user_id) AS user_count,
       ifnull(sum(e.hk),0) AS hk_sum,
       count(e.hk >0) AS hk_count,
       ifnull(sum(d.tz),0) tz_sum,
       count(tz>0) tz_count,
       ifnull(sum(j.sdcl),0) wfbcl_sum,
       count(j.sdcl>0) wfbcl_count,
       ifnull(sum(jj.sdcl),0) whkcl_sum,
       count(jj.sdcl>0) whkcl_count,
       sum(CASE WHEN e.hk > d.tz THEN e.hk-d.tz ELSE 0 END) ls_sum,
       count((e.hk-d.tz)>0) ls_count,
       ifnull(sum(CASE WHEN e.hk >d.tz THEN d.tz ELSE e.hk END),0) xt_sum,
       count((CASE WHEN e.hk >d.tz THEN d.tz ELSE e.hk END)>0) xt_count,
       sum(CASE WHEN ifnull(d.tz,0) > ifnull(e.hk,0) THEN ifnull(d.tz,0)-ifnull(e.hk,0) ELSE 0 END) xz_sum,
       count((CASE WHEN ifnull(d.tz,0)>ifnull(e.hk,0) THEN ifnull(d.tz,0)-ifnull(e.hk,0) ELSE NULL END)) xz_count,
       ifnull(sum(k.sdcl),0) sdcl_sum,
       count(k.sdcl>0) sdcl_count
FROM `user_info` AS `a`
LEFT JOIN
  (SELECT b.user_id,
          sum(b.invest_money) AS tz
   FROM projects_user AS b
   WHERE b.invest_time >= '".$query['start_time']."'
     AND b.invest_time <= '".$query['end_time']."'
   GROUP BY b.user_id) AS d ON `a` . `user_id` = `d` . `user_id`
LEFT JOIN
  (SELECT pp.user_id,
          sum(pp.money) AS hk
   FROM project_profits AS pp
   WHERE (pp.type = 1
          AND pp.pay_time IS NULL
          AND pp.input_time >= '".$query['start_time']."'
          AND pp.input_time <= '".$query['end_time']."') or(pp.type = 1
                                                         AND pp.pay_time IS NOT NULL
                                                         AND pp.pay_time >= '".$query['start_time']."'
                                                         AND pp.pay_time <= '".$query['end_time']."')
   GROUP BY pp.user_id) AS e ON `a` . `user_id` = `e` . `user_id`
LEFT JOIN
  (SELECT pp.user_id,
          sum(pp.money) AS sdcl
   FROM project_profits AS pp
   LEFT JOIN projects AS ps ON pp.project_id = ps.id
   WHERE pp.type = 1
     AND ps.interest_at IS NOT NULL
     AND ps.interest_at <= '".$query['cl_time']."'
     AND(pp.pay_time IS NULL
         OR pp.pay_time >= '".$query['cl_time']."')
   GROUP BY pp.user_id) AS k ON `a` . `user_id` = `k` . `user_id`
LEFT JOIN
  (SELECT h.user_id,
          sum(h.invest_money) AS sdcl
   FROM projects_user AS h
   LEFT JOIN projects AS i ON h.projects_id = i.id
   WHERE i.status = 'rush'
     OR i.status = 'full'
   GROUP BY h.user_id) AS j ON `a` . `user_id` = `j` . `user_id`
 LEFT JOIN
  (SELECT hh.user_id,
          sum(hh.invest_money) AS sdcl
   FROM projects_user AS hh
   LEFT JOIN projects AS ii ON hh.projects_id = ii.id
   WHERE ii.status = 'rush'
     OR ii.status = 'full'
     or ii.status = 'payment' or ii.status = 'late' 
   GROUP BY hh.user_id) AS jj ON `a` . `user_id` = `jj` . `user_id`
LEFT JOIN `users` AS `f` ON `a` . `user_id` = `f` . `id`
LEFT JOIN
  (SELECT l.user_id,
          count(l.id) AS tzbs
   FROM projects_user AS l
   WHERE l.invest_time >= '".$query['start_time']."'
     AND l.invest_time <= '".$query['end_time']."'
   GROUP BY l.user_id) AS m ON `a` . `user_id` = `m` . `user_id`
LEFT JOIN `user_info` AS `jjrb` ON `a` . `broker_code` = `jjrb` . `invite_code`
LEFT JOIN `user_info` AS `jjrb_two` ON `a` . `second_broker_code` = `jjrb_two` . `invite_code`
WHERE (`f` . `username` LIKE '%%'
       OR `f` . `phone_number` LIKE '%%'
       OR `f` . `email` LIKE '%%'
       OR `a` . `name` LIKE '%%')
GROUP BY a.org_code";

// dd($sql);

        $org_user = OrganizationalUser::leftJoin(DB::raw("(".$sql.") as original_table"), 'original_table.org_code', '=', 'organizational_users.code');

        //查询列
        $org_user = $org_user->select(DB::raw('
            organizational_users.code simple_code
            ,organizational_users.company_name
            ,original_table.user_count number_of_members
            ,original_table.broker_count number_of_brokers
            ,original_table.broker_two_count number_of_two_level_brokers
            ,original_table.sdcl_sum total_stock
            ,original_table.tz_sum total_transactions
            ,original_table.hk_sum maturity_amount
            ,original_table.wfbcl_sum the_current_transaction_is_not_established
            ,original_table.whkcl_sum non_repayment_transaction
            ,original_table.ls_sum loss_amount,original_table.xt_sum continued_investment_amount
            ,original_table.xz_sum add_amount'));

        //追加查询条件
        if(!empty($query['org_name']))
            $org_user = $org_user->where('organizational_users.company_name', 'like', '%'.$query['org_name'].'%');

        if(!empty($query['org_code']))
            $org_user = $org_user->where('organizational_users.code', '%'.$query['org_code'].'%');

        if($download == 'download'){
            qeury_export_excel('机构销售统计', $org_user->get());
        }

        $org_user = $org_user->paginate(15);

        $links = $org_user->render();

        return view('admin.business.organizational_manager.org_list', compact('org_user', 'query', 'links'));
    }

    /**
     * 
     * 查询机构下面的所有部门
     * 
     * @return [type] [description]
     */
    public function deptList(Request $request, String $download = ''){

        $query = $this->queryRestriction($request->only('org_name', 'org_code', 'dept_code', 'cl_time', 'start_time', 'end_time'));

       $sql = "SELECT a.dept_code,
        count(distinct(jjrb.user_id)) AS broker_count,
        count(distinct(jjrb_two.user_id)) AS broker_two_count,
       count(a.user_id) AS user_count,
       ifnull(sum(e.hk),0) AS hk_sum,
       count(e.hk >0) AS hk_count,
       ifnull(sum(d.tz),0) tz_sum,
       count(tz>0) tz_count,
       ifnull(sum(j.sdcl),0) wfbcl_sum,
       count(j.sdcl>0) wfbcl_count,
       ifnull(sum(jj.sdcl),0) whkcl_sum,
       count(jj.sdcl>0) whkcl_count,
       sum(CASE WHEN e.hk > d.tz THEN e.hk-d.tz ELSE 0 END) ls_sum,
       count((e.hk-d.tz)>0) ls_count,
       ifnull(sum(CASE WHEN e.hk >d.tz THEN d.tz ELSE e.hk END),0) xt_sum,
       count((CASE WHEN e.hk >d.tz THEN d.tz ELSE e.hk END)>0) xt_count,
       sum(CASE WHEN ifnull(d.tz,0) > ifnull(e.hk,0) THEN ifnull(d.tz,0)-ifnull(e.hk,0) ELSE 0 END) xz_sum,
       count((CASE WHEN ifnull(d.tz,0)>ifnull(e.hk,0) THEN ifnull(d.tz,0)-ifnull(e.hk,0) ELSE NULL END)) xz_count,
       ifnull(sum(k.sdcl),0) sdcl_sum,
       count(k.sdcl>0) sdcl_count
FROM `user_info` AS `a`
LEFT JOIN
  (SELECT b.user_id,
          sum(b.invest_money) AS tz
   FROM projects_user AS b
   WHERE b.invest_time >= '".$query['start_time']."'
     AND b.invest_time <= '".$query['end_time']."'
   GROUP BY b.user_id) AS d ON `a` . `user_id` = `d` . `user_id`
LEFT JOIN
  (SELECT pp.user_id,
          sum(pp.money) AS hk
   FROM project_profits AS pp
   WHERE (pp.type = 1
          AND pp.pay_time IS NULL
          AND pp.input_time >= '".$query['start_time']."'
          AND pp.input_time <= '".$query['end_time']."') or(pp.type = 1
                                                         AND pp.pay_time IS NOT NULL
                                                         AND pp.pay_time >= '".$query['start_time']."'
                                                         AND pp.pay_time <= '".$query['end_time']."')
   GROUP BY pp.user_id) AS e ON `a` . `user_id` = `e` . `user_id`
LEFT JOIN
  (SELECT pp.user_id,
          sum(pp.money) AS sdcl
   FROM project_profits AS pp
   LEFT JOIN projects AS ps ON pp.project_id = ps.id
   WHERE pp.type = 1
     AND ps.interest_at IS NOT NULL
     AND ps.interest_at <= '".$query['cl_time']."'
     AND(pp.pay_time IS NULL
         OR pp.pay_time >= '".$query['cl_time']."')
   GROUP BY pp.user_id) AS k ON `a` . `user_id` = `k` . `user_id`
LEFT JOIN
  (SELECT h.user_id,
          sum(h.invest_money) AS sdcl
   FROM projects_user AS h
   LEFT JOIN projects AS i ON h.projects_id = i.id
   WHERE i.status = 'rush'
     OR i.status = 'full'
   GROUP BY h.user_id) AS j ON `a` . `user_id` = `j` . `user_id`
 LEFT JOIN
  (SELECT hh.user_id,
          sum(hh.invest_money) AS sdcl
   FROM projects_user AS hh
   LEFT JOIN projects AS ii ON hh.projects_id = ii.id
   WHERE ii.status = 'rush'
     OR ii.status = 'full'
     or ii.status = 'payment' or ii.status = 'late'
   GROUP BY hh.user_id) AS jj ON `a` . `user_id` = `jj` . `user_id`
LEFT JOIN `users` AS `f` ON `a` . `user_id` = `f` . `id`
LEFT JOIN
  (SELECT l.user_id,
          count(l.id) AS tzbs
   FROM projects_user AS l
   WHERE l.invest_time >= '".$query['start_time']."'
     AND l.invest_time <= '".$query['end_time']."'
   GROUP BY l.user_id) AS m ON `a` . `user_id` = `m` . `user_id`
LEFT JOIN `user_info` AS `jjrb` ON `a` . `broker_code` = `jjrb` . `invite_code`
LEFT JOIN `user_info` AS `jjrb_two` ON `a` . `second_broker_code` = `jjrb_two` . `invite_code`
WHERE (`f` . `username` LIKE '%%'
       OR `f` . `phone_number` LIKE '%%'
       OR `f` . `email` LIKE '%%'
       OR `a` . `name` LIKE '%%')
GROUP BY a.dept_code";

        //查询所有的部门信息
        $data = DB::table('codes as dept')->leftJoin(DB::raw('('.$sql.') as dept_table'), 'dept.code', '=', 'dept_table.dept_code')->leftJoin('organizational_users as enterprise', 'enterprise.code', '=', 'dept.parent_code')->where('dept.type_id', 'DEPARTMENT')->whereNotNull('dept.parent_code');


        //追加查询条件
        if(!empty($query['org_code']))
            $data = $data->where('enterprise.code', $query['org_code']);

        if(!empty($query['dept_code']))
            $data = $data->where('dept.code', $query['dept_code']);

        //查询的列
        $data = $data->select(DB::raw('
            enterprise.company_name
            ,enterprise.code org_code
            ,dept.code dept_code
            ,dept.name dept_name
            ,dept_table.user_count number_of_members
            ,dept_table.broker_count number_of_brokers
            ,dept_table.broker_two_count number_of_two_level_brokers
            ,dept_table.sdcl_sum total_stock
            ,dept_table.tz_sum total_transactions
            ,dept_table.hk_sum maturity_amount
            ,dept_table.wfbcl_sum the_current_transaction_is_not_established
            ,dept_table.whkcl_sum non_repayment_transaction
            ,dept_table.ls_sum loss_amount
            ,dept_table.xt_sum continued_investment_amount
            ,dept_table.xz_sum add_amount'));

        if($download == 'download'){
            qeury_export_excel('部门销售统计', $data->get());
        }
        //
        $deptList = $data->paginate(15);
        // dd($deptList);
        $links = $deptList->render();

        //查询所有的营销机构
        $all_org = OrganizationalUser::all();

        return view('admin.business.organizational_manager.dept_list', compact('deptList', 'links', 'query', 'all_org'));
    }

    /**
     * 查询所有的经纪人信息
     * 
     * @return [type] [description]
     */
    public function brokerList(Request $request, String $download = ''){
        $query = $this->queryRestriction($request->only('org_name', 'org_code', 'dept_code', 'cl_time', 'start_time', 'end_time', 'broker_name'));

       $sql = "SELECT a.broker_code,
       a.name,
       a.user_id,
        count(distinct(jjrb.user_id)) AS broker_count,
        count(distinct(jjrb_two.user_id)) AS broker_two_count,
       count(a.user_id) AS user_count,
       ifnull(sum(e.hk),0) AS hk_sum,
       count(e.hk >0) AS hk_count,
       ifnull(sum(d.tz),0) tz_sum,
       count(tz>0) tz_count,
       ifnull(sum(j.sdcl),0) wfbcl_sum,
       count(j.sdcl>0) wfbcl_count,
       ifnull(sum(jj.sdcl),0) whkcl_sum,
       count(jj.sdcl>0) whkcl_count,
       sum(CASE WHEN e.hk > d.tz THEN e.hk-d.tz ELSE 0 END) ls_sum,
       count((e.hk-d.tz)>0) ls_count,
       ifnull(sum(CASE WHEN e.hk >d.tz THEN d.tz ELSE e.hk END),0) xt_sum,
       count((CASE WHEN e.hk >d.tz THEN d.tz ELSE e.hk END)>0) xt_count,
       sum(CASE WHEN ifnull(d.tz,0) > ifnull(e.hk,0) THEN ifnull(d.tz,0)-ifnull(e.hk,0) ELSE 0 END) xz_sum,
       count((CASE WHEN ifnull(d.tz,0)>ifnull(e.hk,0) THEN ifnull(d.tz,0)-ifnull(e.hk,0) ELSE NULL END)) xz_count,
       ifnull(sum(k.sdcl),0) sdcl_sum,
       count(k.sdcl>0) sdcl_count
FROM `user_info` AS `a`
LEFT JOIN
  (SELECT b.user_id,
          sum(b.invest_money) AS tz
   FROM projects_user AS b
   WHERE b.invest_time >= '".$query['start_time']."'
     AND b.invest_time <= '".$query['end_time']."'
   GROUP BY b.user_id) AS d ON `a` . `user_id` = `d` . `user_id`
LEFT JOIN
  (SELECT pp.user_id,
          sum(pp.money) AS hk
   FROM project_profits AS pp
   WHERE (pp.type = 1
          AND pp.pay_time IS NULL
          AND pp.input_time >= '".$query['start_time']."'
          AND pp.input_time <= '".$query['end_time']."') or(pp.type = 1
                                                         AND pp.pay_time IS NOT NULL
                                                         AND pp.pay_time >= '".$query['start_time']."'
                                                         AND pp.pay_time <= '".$query['end_time']."')
   GROUP BY pp.user_id) AS e ON `a` . `user_id` = `e` . `user_id`
LEFT JOIN
  (SELECT pp.user_id,
          sum(pp.money) AS sdcl
   FROM project_profits AS pp
   LEFT JOIN projects AS ps ON pp.project_id = ps.id
   WHERE pp.type = 1
     AND ps.interest_at IS NOT NULL
     AND ps.interest_at <= '".$query['cl_time']."'
     AND(pp.pay_time IS NULL
         OR pp.pay_time >= '".$query['cl_time']."')
   GROUP BY pp.user_id) AS k ON `a` . `user_id` = `k` . `user_id`
LEFT JOIN
  (SELECT h.user_id,
          sum(h.invest_money) AS sdcl
   FROM projects_user AS h
   LEFT JOIN projects AS i ON h.projects_id = i.id
   WHERE i.status = 'rush'
     OR i.status = 'full'
   GROUP BY h.user_id) AS j ON `a` . `user_id` = `j` . `user_id`
 LEFT JOIN
  (SELECT hh.user_id,
          sum(hh.invest_money) AS sdcl
   FROM projects_user AS hh
   LEFT JOIN projects AS ii ON hh.projects_id = ii.id
   WHERE ii.status = 'rush'
     OR ii.status = 'full'
     or ii.status = 'payment' or ii.status = 'late'
   GROUP BY hh.user_id) AS jj ON `a` . `user_id` = `jj` . `user_id`
LEFT JOIN `users` AS `f` ON `a` . `user_id` = `f` . `id`
LEFT JOIN
  (SELECT l.user_id,
          count(l.id) AS tzbs
   FROM projects_user AS l
   WHERE l.invest_time >= '".$query['start_time']."'
     AND l.invest_time <= '".$query['end_time']."'
   GROUP BY l.user_id) AS m ON `a` . `user_id` = `m` . `user_id`
LEFT JOIN `user_info` AS `jjrb` ON `a` . `broker_code` = `jjrb` . `invite_code`
LEFT JOIN `user_info` AS `jjrb_two` ON `a` . `second_broker_code` = `jjrb_two` . `invite_code`
WHERE (`f` . `username` LIKE '%%'
       OR `f` . `phone_number` LIKE '%%'
       OR `f` . `email` LIKE '%%'
       OR `a` . `name` LIKE '%%')
GROUP BY a.broker_code";

        //查询所有的部门信息
        $data = SuperUserInfo::leftJoin(DB::raw('('.$sql.') as broker_table'), 'broker_table.broker_code', '=', 'user_info.invite_code')->whereRaw('user_info.invite_code = user_info.broker_code');

        //追加查询条件
        if(!empty($query['broker_name']))
            $data = $data->where('user_info.name', 'like', '%'.$query['broker_name'].'%');

        if(!empty($query['dept_code']))
            $data = $data->where('user_info.dept_code',$query['dept_code']);

        if(!empty($query['org_code']))
            $data = $data->where('user_info.org_code', $query['org_code']);

        //查询的列
        $data = $data->select(DB::raw('
            user_info.name
            ,user_info.org_code
            ,user_info.user_id
            ,broker_table.user_count number_of_members
            ,broker_table.broker_count number_of_brokers
            ,broker_table.broker_two_count number_of_two_level_brokers
            ,broker_table.sdcl_sum total_stock
            ,broker_table.tz_sum total_transactions
            ,broker_table.hk_sum maturity_amount
            ,broker_table.wfbcl_sum the_current_transaction_is_not_established
            ,broker_table.whkcl_sum non_repayment_transaction
            ,broker_table.ls_sum loss_amount
            ,broker_table.xt_sum continued_investment_amount
            ,broker_table.xz_sum add_amount'))
        ->orderBy('broker_table.sdcl_sum', 'desc')
        ->orderBy('broker_table.tz_sum', 'desc')
        ->orderBy('broker_table.hk_sum', 'desc')
        ->orderBy('broker_table.whkcl_sum', 'desc')
        ->orderBy('broker_table.wfbcl_sum', 'desc');

        if($download == 'download'){
            if($this->user->hasRole('RXYX')){
              $data = $data->where('user_info.org_code', $this->RXYX_CODE);
            }
            qeury_export_excel('经济人销售统计', $data->get());
        }
        //
        $brokerList = $data
        ->paginate(15);

        $links = $brokerList->render();

        //查询所有的营销机构
        $all_org = OrganizationalUser::all();

        return view('admin.business.organizational_manager.broker_list', compact('brokerList', 'links', 'query', 'all_org'));
    }

    public function userList(Request $request, String $download = ''){  
      $query = $this->queryRestriction($request->only('name', 'id_card', 'userKey', 'is_set_pay_password','id_card','is_set_phone','is_set_bankcard','is_set_bankcard','p_start_at', 'p_end_at','reg_start_at', 'reg_end_at'));
        $query['download'] = $download;

        $users = User::paging_query($query);

        if (!empty($query))
            $users = $users->appends($query);

        $links = $users->render();

        return view('admin.business.organizational_manager.user_list', compact('query', 'users', 'links'));
    }

    public function create()
    {
        return view('admin.business.organizational_user.create');
    }

    public function store(OrganizationalUserRequest $request)
    {

        DB::beginTransaction();
        try {
            //获取请求参数
            $args = $request->all();

            //创建唯一审核订单号(sina)
            $args['audit_order_no'] = 'order_' . microtme_format('YmdHisx');

            //创建用户唯一标识符(sina_uid)
            $args['identity_id'] = createSinaIdentityId();

            //保存图片
            foreach ($this->imgParameter($request, $args['identity_id']) as $key => $value) {
                $args[$key] = $value;
            }

            //获取用户基本信息参数
            $args2 = [
                'username' => $args['username'],
                'password' => bcrypt(md5($args['password'])),
                'identity_id' => $args['identity_id'],
                'scope' => 'front',
            ];

            //保存用户基本信息表
            $user = new User($args2);
            $user->save();


            //保存机构用户角色信息
            $roles = $request->input('roles');
            foreach ($roles as $key => $value) {
                DB::insert('insert into role_user value('.$user->id.','.$value.')');
            }

            //创建企业会员
             $result = CreateActivateMember::send(['identity_id' => $args['identity_id'], 'identity_type' => 'UID','member_type' => 2]);

             if ($result['response_code'] != 'APPLY_SUCCESS') {
                abort(600,$result['response_message']);
            }

            //获取用户UID
            $args['user_id'] = $user->id;

            //保存审核状态
            $args['status'] = 'PROCESSING';     //审核中....

            //随机生成机构简码
            $args['code'] = create_code(6);

            //实例化机构用户
            $organizationalUser = new OrganizationalUser($args);

            $organizationalUser->save();        //将机构用户保存至数据库


            //生成默认机构 部门
            $code = new Code(['code' => $organizationalUser->code, 'name' => $organizationalUser->company_name, 'type_id' => 'DEPARTMENT', 'description'=>'该机构由系统自动生成...']);
            $code->save();

            $code2 = new Code(['code' => create_code(6), 'name' => '默认部门', 'parent_code' => $code->code, 'type_id' => 'DEPARTMENT', 'description'=>'该机构由系统自动生成...']);
            $code2->save();

            $zipPath = public_path() . '/resources/uploads/branch/' . $args['identity_id'] . '.zip';


            //企业会员证件信息压缩zip
            exec('cd ' . public_path() . '/resources/uploads/branch/' . '&& zip -r ' . $args['identity_id'] . ' ' . $args['identity_id']);
            
            //对文件进行摘要计算
            $args['digest'] = md5_file($zipPath);

            AuditMemberInfos::upload($zipPath, $args['identity_id'] . '.zip');            //缺失php扩展库

            $result=AuditMemberInfos::send($this->sinaParameter($args));

            if($result['response_code'] != 'APPLY_SUCCESS'){
                abort(600,$result['response_message']);
            }

            //完成
            DB::commit();

            Flash::success('机构用户创建成功,请耐心等待审核......');
            return $this->redirectAction('Business\OrganizationalUserManagementController@index');
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    public function edit(Request $request, int $id)
    {
        //根据用户id查询用户
        $user = User::findOrFail($id);
        // //根据用户id查询机构用户权限
        // $roles = DB::table('role_user')->where('user_id', $id)->select('role_id')->get();

        return view('admin.business.organizational_user.edit', compact('user'));
    }
    /**
     * 查询机构用户详情
     * 
     * @return [type] [description]
     */
    public function show(int $id){
        //根据用户id查询用户
        $user = User::findOrFail($id);

        return view('admin.business.organizational_user.show', compact('user'));
    }

    public function update(Request $request, int $id)
    {
        try {
            DB::beginTransaction();
            //查询该机构用户
            $user = User::findOrFail($id);

            //获取请求参数
            $args = $request->all();

            //创建唯一审核订单号(sina)
            $args['audit_order_no'] = 'order_' . microtme_format('YmdHisx');

            //保存图片
            foreach ($this->imgParameter($request, $user->identity_id) as $key => $value) {
                $args[$key] = $value;
            }

            //清除机构用户角色信息
            DB::delete('delete from role_user where user_id = '.$user->id);
            
            //保存机构用户角色信息
            $roles = $request->input('roles');
            foreach ($roles as $key => $value) {
                DB::insert('insert into role_user value('.$user->id.','.$value.')');
            }

            //将审核状态修改为 审核中
            $args['status'] = 'PROCESSING';
            $args['identity_id'] = $user->identity_id;

            //修改机构用户
            $user->organizationalInfo->update($args);

             //企业会员证件信息压缩zip
            exec('cd ' . public_path() . '/resources/uploads/branch/' . '&& zip -r ' . $user->identity_id . ' ' . $user->identity_id);

            //上传企业会员证件信息压缩文件
            $zipPath = public_path() . '/resources/uploads/branch/' . $user->identity_id. '.zip';
            $args['digest'] = md5_file($zipPath);
            AuditMemberInfos::upload($zipPath,$user->identity_id.'.zip');

            //重新发送企业会员审核
            $result = AuditMemberInfos::send($this->sinaParameter($args));

            if($result['response_code'] != 'APPLY_SUCCESS'){
                abort(600,$result['response_message']);
            }

            DB::commit();

            Flash::success('机构用户修改成功,请耐心等待审核......');
            return $this->redirectAction('Business\OrganizationalUserManagementController@index');

        } catch (Exception $e) {
            DB::rollback();
            throw $e;
            
        }
}

    /**
     *
     * 获取并组合出 sina_pay 需要的请求参数
     *
     * @param array $args
     * @return array
     */
    protected function sinaParameter(array $args)
    {
        $data =
            [
                //基本参数
                'service' => 'audit_member_infos',              //接口名称
                'sign' => '',                                       //签名
                'sign_type' => 'RSA',                           //签名方式
                'sign_version' => '1.0',                        //签名版本号 1.0
                'encrypt_version' => '1.0',                     //加密版本号
                'notify_url' => 'https://' . $_SERVER['SERVER_NAME'] . '/sina_pay/in/corporate_membership_audit',    //企业会员审核通知
                'return_url' => '',                             //页面跳转同步返回页面返回路径
                'memo' => '',                                   //说明信息,原文返回

                //企业会员审核业务参数
                'audit_order_no' => $args['audit_order_no'],    //请求审核订单号
                'identity_id' => $args['identity_id'],          //用户标志信息
                'identity_type' => 'UID',                       //用户标识信息
                'member_type' => '2',                           //会员类型,2为企业
                'company_name' => $args['company_name'],        //公司名称
//                'website' => $args['website'],                  //公司网址
                'address' => $args['address'],                  //企业地址
                'license_no' => $args['license_no'],            //执照号
                'license_address' => $args['license_address'],  //营业执照所在地
                'license_expire_date' => '20160813',  //执照过期日(营业期限)
                'business_scope' => $args['business_scope'],            //营业范围
                'telephone' => $args['telephone'],                      //联系电话
                'email' => $args['email'],                              //联系Email
                'organization_no' => $args['organization_no'],          //组织机构代码
                'summary' => $args['summary'],                          //企业简介
                'legal_person' => $args['legal_person'],                //企业法人
                'cert_no' => $args['cert_no'],                          //法人证件号码
                'cert_type' => 'IC',                                    //证件类型,IC身份证
                'legal_person_phone' => $args['legal_person_phone'],    //法人手机号码
                'bank_code' => $args['bank_code'],                      //银行编号
                'bank_account_no' => $args['bank_account_no'],          //银行卡号
                'card_type' => 'DEBIT',                                 //卡类型(DEBIT借记卡)
                'card_attribute' => 'B',                                //卡属性C对公
                'province' => $args['province'],                        //开户行身份
                'city' => $args['city'],                                //开户行城市
                'bank_branch' => $args['bank_branch'],                  //支行名称
                'fileName' => $args['identity_id'] . '.zip',              //文件名称
                'digest' => $args['digest'],                            //文件摘要
                'digestType' => 'MD5',                                  //文件摘要算法
            ];
    

        //去除空参数
        foreach ($data as $key => $value) {
            if (empty($value)) {
                unset($data[$key]);
            }
        }

        return $data;
    }

    /**
     * 保存请求中的文件信息
     *
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function imgParameter(Request $request, string $identity_id)
    {
        $imagePath = 'branch/' . $identity_id;
        $result = ['imagePath' => $imagePath];

        upload_file()->configure(['directory' => $imagePath, 'timestamp' => false]);
        foreach ($request->file() as $key => $item) {
            $type = $item->getClientOriginalExtension();
            //保存企业营业执照
            $json = upload_file($item, ['filename' => $key . '.' . $type]);    //上传文件
            $result[$key] = "{$json['file']['full_url']}";
        }


        return $result;
    }

    /**
     * 处理sina 企业会员审核通知
     * 
     * @param  Request $request 
     * @return [type]
     */
    public function sinapay(Request $request){
        try{
            $args = $request->all();


            ksort($args);

            $result = '';
            foreach ($args as $key => $value) {
                $result = $result.'|'.$key.'='.$value;
            }

            Log::info('企业会员审核通知:'.$result);

            if(AuditMemberInfos::checkSignMsg($args)){
                //处理业务逻辑
                if($args['audit_status']=='SUCCESS'){
                    //审核通过
                    $organizationUser = OrganizationalUser::where('audit_order_no', '=', $args['audit_order_no'])->first();

                    $organizationUser->status = 'SUCCESS';
                    $organizationUser->status_info = '';
                    $organizationUser->save();

                }else{
		    $organizationUser = OrganizationalUser::where('audit_order_no', '=',$asgs['audit_order_no'])->first();
                    //审核失败
                    $organizationUser->status = 'FAILED';
                    $organizationUser->status_info = $args['audit_message'];
                    $organizationUser->save();
                }

            }else{
                Log::info('企业会员审核通知:这个通知不是来自sina');
            }            
            return 'SUCCESS';
        }catch(Exception $e){
            Log::error('企业会员审核: '.$e);
        }
    }
    public function createDept(int $id){
        //查询当前机构用户
        $user = User::findOrFail($id);

        return view('admin.business.organizational_user.create_dept',compact('user'));
    }
    /**
     * 添加部门
     * 
     * @param  Request $request [description]
     * @param  int     $org_id      [机构id]
     * @return [type]           [description]
     */
    public function storeDept(Request $request,int $org_id){
        $user = User::findOrFail($org_id);

        $org_code = $user->organizationalInfo->code;

        $code = new Code(['code' => create_code(6),'parent_code' => $org_code, 'name' => $request->input('dept_name'), 'description' => $request->input('description'), 'type_id' => 'DEPARTMENT']);

        $code->save();

        Flash::success('成功添加了一个部门');
        return $this->redirectAction('Business\OrganizationalUserManagementController@deptList',compact('user'));
    }
    /**
     * 查询部门下的经纪人列表
     * 
     * @param  Request $request   [description]
     * @param  int     $id        [description]
     * @param  string  $dept_code [description]
     * @return [type]             [description]
     */
    public function agentList(Request $request, int $id, string $dept_code){
        $query = $request->only('username', 'name');

        //查询经纪人 id
        $agent_id = (DB::select("select id,slug,name from roles where slug = 'Agent'"))[0]->id;
        $query['role_id'] = $agent_id;

        $org_user = User::findOrFail($id);
        $org_code = $org_user->organizationalInfo->code;
        
        //查询部门下面的经纪人
        $userInfos = $org_user->organizationalInfo->deptUserList($dept_code,$query);
        $links = $userInfos->render();

        return view('admin.business.organizational_user.agent_list',compact('userInfos', 'links', 'org_user', 'dept_code', 'query', 'roles'));
    }
    /**
     *  查询指定经纪人下的所有用户
     * 
     * @param  Request $request   [description]
     * @param  int     $org_id    [机构id]
     * @param  string  $dept_code [部门代码]
     * @param  int     $agent_id  [经纪人id]
     * @return [type]             [description]
     */
    // public function userList(Request $request, int $org_id, string $dept_code, int $agent_id){
    //     $query = $request->only('username','name');

    //     //查找经纪人
    //     $agent_user = User::findOrFail($agent_id);

    //     $query['broker_code'] = $agent_user->userInfo->invite_code;

    //     $org_user = user::findOrFail($org_id);

    //     $userInfos = $org_user->organizationalInfo->deptUserList($dept_code,$query);

    //     $links = $userInfos->render();
    //     return view('admin.business.organizational_user.user_list',compact('userInfos', 'dept_code', 'links', 'org_user', 'agent_user', 'query'));
    // }
    public function addAgent(int $org_id, string $dept_code){
        $org_user = User::findOrFail($org_id);

        return view('admin.business.organizational_user.addAgent', compact('org_user', 'dept_code'));
    }

    /**
     * 投资人转经纪人
     * 
     * @param  Request $request   [description]
     * @param  int     $org_id    [description]
     * @param  string  $dept_code [description]
     * @return [type]             [description]
     */
    public function userToAgent(Request $request, int $org_id, string $dept_code){
        if(!$request->has('username')){
            abort(600,'请填写投资人');
        }

        $username = $request->input("username");

        $user = SuperUser::where('username', $username)
            ->orWhere('email', $username)
            ->orWhere('phone_number', $username)
            ->first();

        if(empty($user)||!$user->hasRole('User')||$user->hasRole(['Agent','OperatingPlatform','GuaranteeAgency','MarketingAgency'])){
            abort(600,'投资人用户不存在...');
        }

        if(!$user->isSetPayPassword()){
            abort(600,'未设置支付密码');
        }

        //执行操作
        $org_user = User::findOrFail($org_id);
        $agent_id = (DB::select("select id,slug,name from roles where slug = 'Agent'"))[0]->id;

        DB::beginTransaction();
        try{

            $user->userInfo->update(['org_code' => $org_user->organizationalInfo->code, 'dept_code' => $dept_code, 'broker_code' => $user->userInfo->invite_code]);
            DB::insert('insert into role_user value('.$user->id.','.$agent_id.')');

            DB::commit();
            Flash::success('添加经纪人成功');
            return $this->redirectAction('Business\OrganizationalUserManagementController@agentList',compact('org_id','dept_code'));
        }catch(Exception $e){
            DB::rollback();
            throw $e;
        }
    }
    public function removeAgent(int $org_id, string $dept_code, int $jjr_id){
        $org_user = User::findOrFail($org_id);
        $jjr_user = User::findOrFail($jjr_id);
        return view('admin.business.organizational_user.removeAgent',compact('org_user', 'dept_code', 'jjr_user'));
    }
    /**
     * 投资人转经纪人
     * 
     * @param  Request $request   [description]
     * @param  int     $org_id    [description]
     * @param  string  $dept_code [description]
     * @return [type]             [description]
     */
    public function agentToUser(Request $request, int $org_id, string $dept_code, string $jjr_id){

        if(!$request->has('gsjjrname')){
            abort(600,'请填写归属经纪人');
        }

        $gsjjrname = $request->input('gsjjrname');

        $jjr_user = User::findOrFail($jjr_id);

        if(empty($jjr_user)||!$jjr_user->hasRole('Agent')){
            abort(600,'原经纪人用户不存在...');
        }

        $gsjjr_user = User::where('username', $gsjjrname)
            ->orWhere('email', $gsjjrname)
            ->orWhere('phone_number', $gsjjrname)
            ->first();

        if(empty($gsjjr_user)||!$gsjjr_user->hasRole('Agent')){
            abort(600,'归属经纪人用户不存在...');
        }

        $agent_id = (DB::select("select id,slug,name from roles where slug = 'Agent'"))[0]->id;
        //数据校验正确,执行变更操作
        DB::beginTransaction();
        try{
            //更改原经纪人 部门 机构 经纪人id 
            $jjr_user->userInfo->update(['broker_code' => $gsjjr_user->userInfo->invite_code, 'org_code' => $gsjjr_user->userInfo->org_code, 'dept_code' => $gsjjr_user->userInfo->dept_code]);
            //移除原经纪人(Agent)角色
            DB::table('role_user')->where('role_id', '=', $agent_id)->where('user_id', '=', $jjr_user->id)->delete();
            //更改原经纪人旗下(投资人) 部门 机构 经纪人id
            UserInfo::where('broker_code', '=', $jjr_user->userInfo->invite_code)->update(['broker_code' => $gsjjr_user->userInfo->invite_code, 'org_code' => $gsjjr_user->userInfo->org_code, 'dept_code' => $gsjjr_user->userInfo->dept_code]);

            DB::commit();
            Flash::success('经纪人转投资人成功');
            return $this->redirectAction('Business\OrganizationalUserManagementController@agentList',compact('org_id','dept_code'));
        }catch(Exception $e){
            DB::rollback();
            throw $e;
        }
    }
    public function changeOrganizational(int $org_id, string $dept_code, int $jjr_id){
        $org_user = User::findOrFail($org_id);
        $jjr_user = User::findOrFail($jjr_id);

        $all_org = OrganizationalUser::all();
        return view('admin.business.organizational_user.changeOrganizational',compact('org_user', 'dept_code', 'jjr_user', 'all_org'));
    }
    public function saveChangeOrganizational(Request $request, int $org_id, string $dept_code, int $jjr_id){
                try{
                    $org_code = $request->input('org_code');
                    $dept_no = $request->input('dept_no');
                }catch(Exception $e){
                        abort(600,'表单信息不完整...');
                }

                    //查询经纪人是否存在
                    $jjr_user = User::findOrFail($jjr_id);

                    if(empty($jjr_user)||!$jjr_user->hasRole('Agent')){
                        abort(600,'经纪人不存在...');
                    }

                    DB::beginTransaction();
                    try {
                        
                    $jjr_user->userInfo->update(['org_code' => $org_code, 'dept_code' =>$dept_no]);
                    $users = UserInfo::where('broker_code', '=', $jjr_user->userInfo->invite_code)->update(['org_code' => $org_code, 'dept_code' =>$dept_no]);

                    DB::commit();
                    Flash::success("经纪人营销部门变更成功!");
                    return $this->redirectAction('Business\OrganizationalUserManagementController@agentList',compact('org_id','dept_code'));
                    } catch (Exception $e) {
                        DB::rollback();
                        throw $e;
                    }
    }
    /**
     * 改变投资人的经纪人
     * 
     * @param  int    $org_id   [description]
     * @param  string $dept_no  [description]
     * @param  int    $agent_id [description]
     * @return [type]           [description]
     */
    public function changeAgent(int $org_id, string $dept_no, int $broker_id, int $user_id){
        //查询投资人用户
        $user = User::findOrFail($user_id);
        return view('admin.business.organizational_user.changeOldAgent', compact('user', 'org_id', 'dept_no', 'broker_id'));
    }
    public function saveChangeAgent(Request $request,int $org_id, string $dept_no, int $broker_id, int $user_id){
        if(!$request->has('gsjjrname')){
            abort(600,'请填写归属经纪人');
        }

        $gsjjrname = $request->input('gsjjrname');

        $gsjjr_user = User::where('username', $gsjjrname)
            ->orWhere('email', $gsjjrname)
            ->orWhere('phone_number', $gsjjrname)
            ->first();


        if(empty($gsjjr_user)||!$gsjjr_user->hasRole('Agent')){
                abort(600,'归属经纪人不存在...');
            }

        $user = User::findOrFail($user_id);

        if(empty($user)||!$user->hasRole('User')){
                abort(600,'原投资人不存在...');
            }


        //数据校验正确,开始变更经纪人
        DB::beginTransaction();
        try{
            $user->userInfo->update(['broker_code' => $gsjjr_user->userInfo->invite_code, 'org_code' => $gsjjr_user->userInfo->org_code,'dept_code' => $gsjjr_user->userInfo->dept_code]);
            DB::commit();
            Flash::success("变更投资人的经纪人成功!");
            return $this->redirectAction('Business\OrganizationalUserManagementController@userList',compact('org_id','dept_no','broker_id'));
        }catch(Exception $e){
            DB::rollback();
            throw $e;
        }
    }

    /**
     * 设置机构和经纪人的分润比例
     * 
     * @return [type] [description]
     */
    public function brokerDncomeDistribution(int $org_id){
        //读取该机构的分润比例
        $org = OrganizationalUser::findOrFail($org_id);
        return view('admin.business.organizational_user.broker_income_distribution',compact('org_id','org'));
    }

    /**
     * 保存经纪分润比例
     * @param  Request $request [description]
     * @param  int     $org_id  [description]
     * @return [type]           [description]
     */
    public function saveBrokerDncomeDistribution(Request $request, int $org_id){
        if(!$request->has('profit_ratio')){
            abort(600,'没有填写经纪人分润比例');
        }
        if(!$request->has('org_profit')){
            abort(600,'没有填写机构分润比例');
        }
        if(!$request->has('second_radio')){
            abort(600,'没有填写二级经纪人分润比例');
        }

        $org_user = User::findOrFail($org_id);
        $org_user->organizationalInfo->profit_ratio = $request->input('profit_ratio');
        $org_user->organizationalInfo->org_profit = $request->input('org_profit');
        $org_user->organizationalInfo->second_radio = $request->input('second_radio');
        $org_user->organizationalInfo->save();

        Flash::success('设置经纪人分润比例成功');
        return $this->redirectAction('Business\OrganizationalUserManagementController@index');
    }
    /**
     * 设置机构账户支付密码
     */
    public function setPayPassword(int $org_id){
        $user = User::findOrFail($org_id);
        $result = SetPayPassword::send(['identity_id' => $user->identity_id,'identity_type'=>'UID','return_url'=>config('p2pdefault.web.http').'://'.$_SERVER['SERVER_NAME'].'/admin/business/organizational_user_manager']);
         if($result['response_code'] != 'APPLY_SUCCESS'){
             abort(600,$result['response_message']);
         }


         return redirect($result['redirect_url']);
    }

     /**
     * 查询机构信息
     */
    public function queryMemberInfos(int $org_id){
        $user = User::findOrFail($org_id);
        $result = QueryBalance::send(['identity_id' => $user->identity_id,'identity_type'=>'UID', 'account_type' => 'BASIC','return_url'=>config('p2pdefault.web.http').'://'.$_SERVER['SERVER_NAME'].'/admin/business/organizational_user_manager']);

         if($result['response_code'] != 'APPLY_SUCCESS'){
             abort(600,$result['response_message']);
         } 

         $result2 = QueryBalance::send(['identity_id' => $user->identity_id,'identity_type'=>'UID', 'account_type' => 'SAVING_POT','return_url'=>config('p2pdefault.web.http').'://'.$_SERVER['SERVER_NAME'].'/admin/business/organizational_user_manager']);

         if($result['response_code'] != 'APPLY_SUCCESS'){
             abort(600,$result['response_message']);
         }

         // dd($result2);

            //基本户
         $balance = $result['balance'] ?? 0;
         $available_balance = $result['available_balance'] ?? 0;
         // $temp = explode('^', $result['available_balance']);
         // $bonus = $temp[count($temp)-1];

         //存钱罐
         $balance2 = $result2['balance'] ?? 0;
         $available_balance2 = $result2['available_balance'] ?? 0;
         $temp = explode('^', $result2['available_balance']);
         $bonus = $temp[count($temp)-1];

        return view('admin.business.organizational_user.balance',compact('balance', 'available_balance','balance2', 'available_balance2', 'bonus'));
    }
    /**
     * 查询用户详情
     * @param  int    $id [description]
     * @return [type]     [description]
     */
    public function userInfo(int $id){
        $user = User::findOrFail($id);
        $broker_mame=UserInfo::where('invite_code','=',$user->userInfo->broker_code)->value('name');
        return view('admin.business.organizational_manager.user_info', compact('user','broker_mame'));
    }
}
